package groovy.jmx.builder.modelmbean

import groovy.jmx.builder.node.MBeanNodeData
import javax.management.Descriptor
import javax.management.modelmbean.*




class ModelMBeanCollector {
    public ModelMBeanInfo collectMBeanInfo(MBeanNodeData data) {
        ModelMBeanInfo info;
        if (data) {
            Descriptor desc = new DescriptorSupport()
            desc.setField("name", data?.object.getClass().name)
            desc.setField("descriptorType", "mbean")
            desc.setField("displayName", data.description)

            // add any addtional fields
            data?.value.each {key, value ->
                desc.setField(key, value)
            }

            ModelMBeanAttributeInfo[] attribs = new ModelMBeanAttributeCollector().collectAttributeInfo(data)?.toArray()
            ModelMBeanConstructorInfo[] ctors = new ModelMBeanConstructorCollector().collectConstructorInfo(data)?.toArray()
            ModelMBeanOperationInfo[] ops = new ModelMBeanOperationCollector().collectOperationInfo(data)?.toArray()

            info = new ModelMBeanInfoSupport(
                    data?.object.getClass().name,
                    data.description,
                    attribs,
                    ctors,
                    ops,
                    null,
                    desc)

        }
        return info
    }

    public ModelMBeanInfo collectMBeanInfo(def instance) {
        ModelMBeanInfo info
        if (instance) {
            ModelMBeanAttributeInfo[] attribs = new ModelMBeanAttributeCollector().collectAttributeInfo(instance)?.toArray()
            ModelMBeanConstructorInfo[] ctors = new ModelMBeanConstructorCollector().collectConstructorInfo(instance)?.toArray()
            ModelMBeanOperationInfo[] ops = new ModelMBeanOperationCollector().collectOperationInfo(instance)?.toArray()

            info = new ModelMBeanInfoSupport(
                    instance.class.name,
                    "Class ${instance.class.name}",
                    attribs,
                    ctors,
                    ops,
                    null)
        }
        return info
    }
}